<template>
  <div>
    <Breadcrumb :breadcrumbInfo="breadcrumbInfo"></Breadcrumb>
    <el-card>
      <!-- 添加角色按钮 -->
      <el-button
        class="btn-addrolse"
        type="primary"
        icon="el-icon-edit"
        size="medium "
        @click="addUerInfo.isShow = true"
        >添加角色</el-button
      >
    

    <!-- 表单区域 -->
    <el-table
      :data="DialogForm.rolessList.data"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row
            :class="['vcenter', 'bdbottom', index === 0 ? 'bdtop' : '']"
            v-for="(item1, index) in scope.row.children"
            :key="item1.id"
          >
            <!-- 渲染一级权限 -->
            <el-col :span="8">
              <el-tag closable @close="removeTag(scope.row, item1.id)">
                {{ item1.authName }}</el-tag
              >
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级三级权限 -->
            <el-col :span="10">
              <!-- 渲染二级权限 -->
              <el-row
                :class="['vcenter', 'bdbottom', index2 === 0 ? 'bdtop' : '']"
                v-for="(item2, index2) in item1.children"
                :key="item2.id"
              >
                <el-col :span="10">
                  <el-tag
                    closable
                    type="success"
                    @close="removeTag(scope.row, item2.id)"
                    >{{ item2.authName }}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="10">
                  <el-tag
                    type="warning"
                    :class="[
                      'vcenter',
                      'bdbottom',
                      index3 === 0 ? 'bdtop' : '',
                    ]"
                    v-for="(item3, index3) in item2.children"
                    :key="item3.id"
                    closable
                    @close="removeTag(scope.row, item3.id)"
                    >{{ item3.authName }}</el-tag
                  >
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column width="50" type="index"></el-table-column>
      <el-table-column
        nim-width="280"
        prop="roleName"
        label="角色名称"
        align="center"
      >
      </el-table-column>
      <el-table-column width="380" prop="roleDesc" label="角色描述">
      </el-table-column>
      <el-table-column width="380" prop="level" label="操作" align="center">
        <template slot-scope="scope">
          <!-- 编辑按钮 -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="getEditForm(scope.row.id)"
            >编辑</el-button
          >
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteForm(scope.row.id)"
            >删除</el-button
          >
          <!-- 分配权限按钮 -->
          <el-button
            type="warning"
            icon="el-icon-setting"
            size="mini"
            @click="setRolesRights(scope.row)"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>
</el-card>
    <!-- 编辑dialog表单区 -->
    <Dialog :DialogForm="DialogForm"></Dialog>

    <!-- 添加用户Dialong对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUerInfo.isShow"
      @close="addDialongClose"
    >
      <el-form :model="addUerInfo" label-width="120px" status-icon>
        <el-form-item label="角色名称">
          <el-input v-model="addUerInfo.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" label-width="120px">
          <el-input
            v-model="addUerInfo.description"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="addDialongClose">重 置</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配权限表单 -->

    <el-dialog
      title="权限列表"
      :visible.sync="rolesRightInfo.isShow"
      width="30%"
      @close="setRightsDiaologClose"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rolesRightInfo.allRightList"
        :props="rolesRightInfo.TreeProps"
        :default-checked-keys="rolesRightInfo.TreeKey"
        node-key="id"
        default-expand-all
        show-checkbox
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesRightInfo.isShow = false">取 消</el-button>
        <el-button type="primary" @click="updataRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 引入面包屑导航组件
import Breadcrumb from "../../components/Breadcrumb.vue";
import Dialog from "../../components/Dialog.vue";
export default {
  name: "Roles",
  components: { Breadcrumb, Dialog },
  data() {
    return {
      //添加Dialog表單信息
      addUerInfo: {
        isShow: false,
        username: "",
        description: "",
      },

      //分配权限Dialog表單信息
      rolesRightInfo: {
        isShow: false,
        allRightList: [],
        // 数形状控件
        TreeProps: {
          label: "authName",
          children: "children",
        },
        //数控默认勾选状态
        TreeKey: [],
        // 即将分配权限的角色
        rolesId: "",
      },
      // 面包屑导航消息
      breadcrumbInfo: {
        titlePath: [
          { title: "首页", Path: "/Home" },
          { title: "权限管理", Path: "" },
          { title: "角色列表", Path: "" },
        ],
      },

      // 保存角色Id
      saveRolesID: 0,

      //编辑Dialog表單信息
      DialogForm: {
        // 角色列表
        rolessList: {},
        // 根据 ID 查询角色
        idroles: {},
        // 表单打开信息
        isShow: false,
        // 渲染表单信息且做数据绑定
        DialogTag: [
          { tag: "角色名称", rolesInfo: "" },
          { tag: "角色描述", rolesInfo: "" },
        ],
      },
    };
  },
  methods: {
    //通过递归的形式，获取角色下所有三级权限的id，并保存到TreeKey数组中
    getKeafKeys(node, arr) {
      //判断是否为三级权限
      //如果当前node节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((element) => {
        this.getKeafKeys(element, arr);
      });
    },
    //设置角色权限
    async setRolesRights(role) {
      // 保存设置角色权限的id
      this.rolesRightInfo.rolesId = role.id;

      //获取所有权限数据
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取所有权限数据失败");
      }
      // 把获取到的数据报错到allRightList中
      this.rolesRightInfo.allRightList = res.data;
      // 递归获取三级节点id

      this.getKeafKeys(role, this.rolesRightInfo.TreeKey);
      this.rolesRightInfo.isShow = true;
    },

    // 分配权限的更新
    async updataRights() {
      // 获取树节点key
      const key = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];

      const idStr = key.join(",");

      const { data: res } = await this.$http.post(
        `roles/${this.rolesRightInfo.rolesId}/rights`,
        { rids: idStr }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败");
      }
      this.$message.success("分配权限成功");
      this.getRolesList();

      this.rolesRightInfo.isShow = false;
    },

    // 监听设置权限的关闭
    setRightsDiaologClose() {
      this.rolesRightInfo.TreeKey = [];
    },
    // 删除权限标签
    async removeTag(role, rightId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.error("用户取消");
      }

      const { data: result } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );

      if (result.meta.status !== 200) {
        return this.$message.error("删除权限失败");
      }
      //为了防止整体页面刷新关闭,自己给 role.children 赋值即可
      role.children = result.data;
      this.$message.success("删除权限成功");
    },

    // 关闭添加用户窗口
    addDialongClose() {
      this.addUerInfo.username = "";
      this.addUerInfo.description = "";
    },

    // 添加角色
    addRoles() {
      this.$http
        .post("roles", {
          roleName: this.addUerInfo.username,
          roleDesc: this.addUerInfo.description,
        })
        .then((result) => {
          if (result.data.meta.status != 201)
            return this.$message.error(result.data.meta.msg);
          this.$message.success(result.data.meta.msg);
          this.getRolesList();
        })
        .catch((err) => {
          return this.$message.error(err.data.meta.status);
        });

      this.addUerInfo.isShow = false;
    },

    getEditForm(id) {
      this.$http
        .get("roles/" + id)
        .then((result) => {
          if (result.data.meta.status != 200)
            return this.$message.error(result.data.meta.status);
          // 保存Id查询到的角色
          this.DialogForm.idroles = result.data.data;
        })
        .catch((err) => {
          return this.$message.error(err.data.meta.status);
        });
      this.saveRolesID = id;
      this.DialogForm.isShow = true;
    },
    upEditForm() {
      // 发送服务器编辑提交角色
      this.$http
        .put("roles/" + this.saveRolesID, {
          roleName: this.DialogForm.DialogTag[0].rolesInfo,
          roleDesc: this.DialogForm.DialogTag[1].rolesInfo,
        })
        .then((result) => {
          if (result.data.meta.status != 200)
            return this.$message.error(result.data.meta.msg);
          // 刷新数据列表
          this.getRolesList();
          this.$message.success("编辑更新成功");
        })
        .catch((err) => {
          return this.$message.error(err.data.meta.msg);
        });
    },
    // 删除角色
    deleteForm(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete("roles/" + id).then((response) => {
            if (response.data.meta.status != 200)
              return this.$message.error(response.data.meta.msg);
            this.getRolesList();
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //获取角色列表
    getRolesList() {
      this.$http
        .get("roles")
        .then((result) => {
          if (result.data.meta.status != 200)
            return this.$message.error(result.data.meta.status);
          this.DialogForm.rolessList = result.data;
        })
        .catch((err) => {
          return this.$message.error(err.data.meta.msg);
        });
    },
  },

  mounted() {
    this.$bus.$on("upEditForm", (data) => {
      this.upEditForm();

      this.DialogForm.isShow = false;
    });
  },

  beforeDestroy() {
    // 解绑
    this.$bus.$off("upEditForm");
  },

  created() {
    this.getRolesList();
  },
};
</script>

<style>
.btn-addrolse {
  position: relative;
  left: 80%;
  margin-bottom: 15px;
}

.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 2px solid rgb(240, 238, 238);
}

.bdbottom {
  border-bottom: 2px solid rgb(231, 229, 229);
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>